#!/bin/bash

# Define the path to your OpenVPN configuration file
# IMPORTANT: Change this to the correct path on your system
OVPN_CONFIG="/home/satway/vpn/vpn.mapway.cn.ovpn"

# Define the name of the process to check for
PROCESS_NAME="openvpn-mapway"

# --- Functions ---

start_vpn() {
    echo "Starting OpenVPN connection..."
    # Check if a process with the same config file is already running
    if pgrep -f "$OVPN_CONFIG" > /dev/null; then
        echo "OpenVPN (openvpn-mapway) is already running."
        exit 1
    fi

    # Start the OpenVPN client in daemon mode
    sudo openvpn --config "$OVPN_CONFIG" --daemon

    if [ $? -eq 0 ]; then
        echo "OpenVPN (openvpn-mapway) started successfully."
    else
        echo "Error: Failed to start OpenVPN."
        exit 1
    fi
}

stop_vpn() {
    echo "Stopping OpenVPN connection..."
    # Find the PID of the OpenVPN process
    PID=$(pgrep -f "$OVPN_CONFIG")

    if [ -z "$PID" ]; then
        echo "OpenVPN is not currently running. (openvpn-mapway)"
        exit 1
    fi

    # Kill the process
    sudo kill "$PID"

    if [ $? -eq 0 ]; then
        echo "OpenVPN (openvpn-mapway) stopped successfully."
    else
        echo "Error: Failed to stop OpenVPN (openvpn-mapway)."
        exit 1
    fi
}

status_vpn() {
    if pgrep -f "$OVPN_CONFIG" > /dev/null; then
        echo "OpenVPN is running."
    else
        echo "OpenVPN is not running."
    fi
}

# --- Main Logic ---

case "$1" in
    start)
        start_vpn
        ;;
    stop)
        stop_vpn
        ;;
    status)
        status_vpn
        ;;
    *)
        echo "Usage: $0 {start|stop|status}"
        exit 1
        ;;
esac

exit 0
